"use client";

import { useState, useEffect } from "react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { useLanguage } from "~/lib/LanguageContext";

export type OutputType =
  "diagram" |
  "overview-doc" |
  "detailed-doc" |
  "database-doc" |
  "api-doc" |
  "deployment-doc";

interface OutputTypeSelectorProps {
  onChange: (type: OutputType) => void;
  value: OutputType;
}

export default function OutputTypeSelector({ onChange, value }: OutputTypeSelectorProps) {
  const { t } = useLanguage();
  const [currentValue, setCurrentValue] = useState<OutputType>(value);

  // 当外部value变化时，更新内部状态
  useEffect(() => {
    console.log(`[OutputTypeSelector] 外部value变化: ${value}`);
    setCurrentValue(value);
  }, [value]);

  // 启动时记录当前值
  useEffect(() => {
    console.log(`[OutputTypeSelector] 组件初始化, 当前值: ${value}, 内部状态: ${currentValue}`);
    
    // 记录当前路径和全局状态标记
    if (typeof window !== 'undefined') {
      console.log(`[OutputTypeSelector] 当前路径: ${window.location.pathname}`);
      console.log(`[OutputTypeSelector] 全局标记 - 文档模式: ${!!window._isDocumentMode}, 图表模式: ${!!window._isDiagramMode}`);
    }
  }, []);

  const handleChange = (newValue: string) => {
    console.log(`[OutputTypeSelector] 选中值: ${newValue}, 来自: ${new Error().stack?.split('\n')[2]}`);
    
    if (
      newValue === "diagram" ||
      newValue === "overview-doc" ||
      newValue === "detailed-doc" ||
      newValue === "database-doc" ||
      newValue === "api-doc" ||
      newValue === "deployment-doc"
    ) {
      console.log(`[OutputTypeSelector] 调用onChange, 当前值: ${currentValue}, 新值: ${newValue}`);
      
      // 更新内部状态
      setCurrentValue(newValue as OutputType);
      
      // 根据选择的输出类型设置正确的全局标记
      if (typeof window !== 'undefined') {
        if (newValue === 'diagram') {
          // 设置图表模式标记
          window._isDiagramMode = true;
          // 移除文档模式标记（如果有）
          if (window._isDocumentMode) {
            delete window._isDocumentMode;
          }
          console.log("[OutputTypeSelector] 设置图表模式标记，移除文档模式标记");
        } else {
          // 设置文档模式标记
          window._isDocumentMode = true;
          // 移除图表模式标记（如果有）
          if (window._isDiagramMode) {
            delete window._isDiagramMode;
          }
          
          // 额外记录所选文档类型
          console.log(`[OutputTypeSelector] 选择的文档类型: ${newValue}`);
          // 检查localStorage设置
          if (typeof localStorage !== 'undefined') {
            localStorage.setItem('current_document_type', newValue);
            console.log(`[OutputTypeSelector] 已保存文档类型到localStorage: ${newValue}`);
          }
          
          console.log(`[OutputTypeSelector] 设置文档模式标记，移除图表模式标记`);
        }
      }
      
      // 添加更详细的日志记录onChange调用细节
      console.log(`[OutputTypeSelector-调试] 准备调用onChange函数: 类型=${typeof onChange}, 参数值=${newValue}`);
      // 调用外部回调
      onChange(newValue as OutputType);
      console.log(`[OutputTypeSelector-调试] onChange函数调用完成`);
    }
  };

  // 添加组件挂载时的日志
  console.log(`[OutputTypeSelector] 当前值: ${value}`);

  return (
    <div className="flex items-center gap-3">
      <span className="text-sm font-medium">{t("outputTypeTitle")}</span>
      <Select value={currentValue} onValueChange={handleChange}>
        <SelectTrigger className="w-[200px] rounded-md border-[3px] border-black px-3 py-2 text-sm shadow-[4px_4px_0_0_#000000] dark:border-gray-700 dark:shadow-[4px_4px_0_0_#1f1f1f]">
          <SelectValue placeholder={t("diagramOption")} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="diagram">{t("diagramOption")}</SelectItem>
          <SelectItem value="overview-doc">{t("overviewDocOption")}</SelectItem>
          <SelectItem value="detailed-doc">{t("detailedDocOption")}</SelectItem>
          <SelectItem value="database-doc">{t("databaseDocOption")}</SelectItem>
          <SelectItem value="api-doc">{t("apiDocOption")}</SelectItem>
          <SelectItem value="deployment-doc">{t("deploymentDocOption")}</SelectItem>
        </SelectContent>
      </Select>
    </div>
  );
} 